package com.bwie.shopcar.timing;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.domain.Coupon;
import com.bwie.common.domain.Systems;
import com.bwie.shopcar.service.ShopCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Component
public class TimeingSendMessage {
    @Autowired
    private ShopCarService service;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;

    @Scheduled(cron = "* 0/40 * * * ?")
    public void sendMessage(){
        List<Systems> send = service.sendMessage();
        for (Systems systems1 : send) {
            if (systems1.getSystemMessage().equals("购买成功")) {
                Coupon coupon = new Coupon();
                //随机生成50元之内红包
                Random rand = new Random();
                int randomNumber = rand.nextInt(50);
                coupon.setCouponPacket(randomNumber);
                Integer give = service.giveUserCoupon(coupon);
                if (give > 0) {
                    service.deleteCoupon(systems1.getSystemId());
                }
            }
            //优惠券抽取派发完成，异步发送短信通知到用户
            if (systems1.getSystemNum() < 0) {
                Map<String, String> map = new HashMap<>();
                map.put("发送短信验证码：消息内容是：【{}】",JSONObject.toJSONString(map));
                TelSmsUtils.sendSms("18171594937",map);
            }
        }
    }
}
